<template>
  <div id="app">
    <TopNavbar 
      :is-connected="isConnected"
      :connection="connection"
      :refreshing="refreshing"
      @refresh-indices="loadIndices"
    />
    
    <Sidebar 
      :connection="connection"
      :is-connected="isConnected"
      :connecting="connecting"
      :indices="indices"
      :loading-indices="loading"
      :selected-index="currentView.index"
      :refreshing="refreshing"
      @connect="connectToES"
      @disconnect="disconnect"
      @refresh-indices="loadIndices"
      @select-index="showIndexData"
      @update-connection="updateConnection"
      @show-feedback="showFeedback"
    />
    
    <MainContent
      ref="mainContent"
      :selected-index="currentView.index"
      :is-connected="isConnected"
      :index-data="indexData"
      :loading-data="loading"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="indexData.total"
      @prev-page="prevPage"
      @next-page="nextPage"
      @execute-sql="executeSql"
      @clear-sql="clearSql"
      @execute-dsl="executeDsl"
      @clear-dsl="clearDsl"
    />
    
    <FooterFeedback
      :feedback-message="feedbackMessage"
      :feedback-type="feedbackType"
      @close-feedback="closeFeedback"
    />
  </div>
</template>

<script>
import axios from 'axios'
import TopNavbar from './components/TopNavbar.vue'
import Sidebar from './components/Sidebar.vue'
import MainContent from './components/MainContent.vue'
import FooterFeedback from './components/FooterFeedback.vue'
import './styles/app.css'

// 获取API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || ''

export default {
  name: 'App',
  components: {
    TopNavbar,
    Sidebar,
    MainContent,
    FooterFeedback
  },
  data() {
    return {
      connection: {
        host: '100.116.69.74',
        port: 9200
      },
      isConnected: false,
      connecting: false,
      refreshing: false,
      connectionStatus: '',
      connectionStatusClass: '',
      indices: [],
      loading: false,
      currentView: {
        index: null
      },
      indexData: {
        hits: [],
        total: 0,
        took: 0
      },
      currentPage: 1,
      pageSize: 10,
      sqlQuery: '',
      sqlResult: null,
      dslQuery: '',
      dslResult: null,
      feedbackMessage: '',
      feedbackType: 'success',
      // 添加轮询定时器
      pollingTimer: null,
      pollingInterval: 5000 // 5秒轮询一次
    }
  },
  
  mounted() {
    // 设置axios默认请求头
    this.setupAxiosDefaults();
    // 从localStorage加载保存的连接信息
    this.loadConnectionFromStorage();
    // 启动轮询检查连接状态
    this.startPolling();
  },
  
  beforeUnmount() {
    // 组件销毁前清除定时器
    this.stopPolling();
  },
  
  watch: {
    // 监听连接信息变化，自动保存到localStorage
    'connection.host': function(newHost) {
      this.saveConnectionToStorage();
    },
    'connection.port': function(newPort) {
      this.saveConnectionToStorage();
    }
  },

  methods: {
    // 设置axios默认配置
    setupAxiosDefaults() {
      // 从localStorage获取或生成userId
      let userId = sessionStorage.getItem('userId');
      if (!userId) {
        userId = this.generateUserId();
        localStorage.setItem('userId', userId);
      }
      
      // 设置默认请求头
      axios.defaults.headers.common['X-User-Id'] = userId;
    },
    
    // 生成用户ID
    generateUserId() {
      return 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    },
    
    // 启动轮询
    startPolling() {
      this.stopPolling(); // 先清除已有的定时器
      this.pollingTimer = setInterval(() => {
        if (this.isConnected) {
          this.checkConnectionStatus();
        }
      }, this.pollingInterval);
    },
    
    // 停止轮询
    stopPolling() {
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer);
        this.pollingTimer = null;
      }
    },
    
    // 检查连接状态
    async checkConnectionStatus() {
      try {
        const response = await axios.get(`${API_BASE_URL}/api/es/connection/status`);
        if (!response.data.data) {
          this.isConnected = false;
          this.showFeedback('与Elasticsearch的连接已断开', 'error');
        }
      } catch (error) {
        this.isConnected = false;
        this.showFeedback('检查连接状态失败: ' + error.message, 'error');
      }
    },
    
    // 保存连接信息到localStorage
    saveConnectionToStorage() {
      try {
        const connectionData = {
          host: this.connection.host,
          port: this.connection.port
        };
        localStorage.setItem('esConnection', JSON.stringify(connectionData));
      } catch (e) {
        console.warn('无法保存连接信息到localStorage:', e);
      }
    },
    
    // 从localStorage加载连接信息
    loadConnectionFromStorage() {
      try {
        const savedConnection = localStorage.getItem('esConnection');
        if (savedConnection) {
          const connectionData = JSON.parse(savedConnection);
          this.connection.host = connectionData.host || this.connection.host;
          this.connection.port = connectionData.port || this.connection.port;
        }
      } catch (e) {
        console.warn('无法从localStorage加载连接信息:', e);
      }
    },
    
    updateConnection(newConnection) {
      this.connection = { ...newConnection };
    },
    
    async connectToES(connection) {
      try {
        this.connecting = true;
        const response = await axios.post(`${API_BASE_URL}/api/es/connect`, {
          host: connection.host,
          port: parseInt(connection.port)
        })
        
        if (response.data.success) {
          this.isConnected = true
          this.showFeedback('连接成功', 'success');
          // 连接成功后自动加载索引
          this.loadIndices()
        } else {
          this.isConnected = false
          this.showFeedback(response.data.message, 'error');
        }
      } catch (error) {
        this.isConnected = false
        this.showFeedback('连接失败: ' + (error.response?.data?.message || error.message), 'error');
      } finally {
        this.connecting = false;
      }
    },
    
    disconnect() {
      this.isConnected = false;
      this.indices = [];
      this.currentView.index = null;
      this.showFeedback('已断开连接', 'success');
    },
    
    async loadIndices() {
      if (!this.isConnected) return
      
      this.loading = true
      this.refreshing = true
      try {
        const response = await axios.get(`${API_BASE_URL}/api/es/indices`)
        if (response.data.success) {
          this.indices = response.data.data || []
        } else {
          this.showFeedback('加载索引失败: ' + response.data.message, 'error');
          this.indices = []
        }
      } catch (error) {
        console.error('加载索引失败:', error)
        this.showFeedback('加载索引失败: ' + (error.response?.data?.message || error.message), 'error');
        this.indices = []
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    
    async showIndexData(indexName) {
      this.loading = true
      this.currentView.index = indexName
      this.currentPage = 1
      await this.loadIndexData()
    },
    
    async loadIndexData() {
      try {
        const from = (this.currentPage - 1) * this.pageSize
        const response = await axios.get(`${API_BASE_URL}/api/es/indices/${this.currentView.index}/data`, {
          params: {
            from: from,
            size: this.pageSize
          }
        })
        if (response.data.success) {
          this.indexData = response.data.data || { hits: [], total: 0, took: 0 }
        } else {
          this.showFeedback('加载索引数据失败: ' + response.data.message, 'error');
          this.indexData = { hits: [], total: 0, took: 0 }
        }
      } catch (error) {
        console.error('加载索引数据失败:', error)
        this.showFeedback('加载索引数据失败: ' + (error.response?.data?.message || error.message), 'error');
        this.indexData = { hits: [], total: 0, took: 0 }
      } finally {
        this.loading = false
      }
    },
    
    async prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.loading = true
        await this.loadIndexData()
      }
    },
    
    async nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.loading = true
        await this.loadIndexData()
      }
    },
    
    async executeSql(sql) {
      if (!sql.trim()) return;
      
      try {
        this.loading = true;
        const response = await axios.post(`${API_BASE_URL}/api/es/sql`, {
          sql: sql
        });
        this.sqlResult = response.data;
        
        // 检查响应数据中是否有 success 字段，如果没有默认为 true
        const isSuccess = response.data.success !== undefined ? response.data.success : true;
        if (isSuccess) {
          // 确保 indexData.hits 是一个数组后再使用 forEach
          if (response.data.data && response.data.data.hits && Array.isArray(response.data.data.hits)) {
            this.indexData = response.data.data;
          } else {
            // 如果没有 hits 数组，创建一个空数组
            this.indexData = {
              hits: [],
              total: (response.data.data && response.data.data.total) || 0,
              took: (response.data.data && response.data.data.took) || 0
            };
          }
          this.showFeedback(`SQL执行成功，返回${(response.data.data && response.data.data.total) || 0}条数据，耗时${(response.data.data && response.data.data.took) || 0}ms`, 'success');
        } else {
          // 确保 response.data.message 存在
          const errorMessage = response.data.message || '未知错误';
          this.showFeedback(`SQL执行失败: ${errorMessage}`, 'error');
        }
      } catch (error) {
        console.error('执行SQL失败:', error);
        this.sqlResult = {
          success: false,
          message: '执行SQL失败: ' + (error.response?.data?.message || error.message)
        };
        this.showFeedback('执行SQL失败: ' + (error.response?.data?.message || error.message), 'error');
      } finally {
        this.loading = false;
        // 发送事件通知MainContent组件执行完成
        if (this.$refs && this.$refs.mainContent) {
          this.$refs.mainContent.executingSql = false;
        }
      }
    },
    
    clearSql() {
      this.sqlQuery = '';
      this.sqlResult = null;
    },
    
    async executeDsl(dsl) {
      if (!dsl.trim()) return;
      
      try {
        this.loading = true;
        const response = await axios.post(`${API_BASE_URL}/api/es/dsl`, {
          dsl: dsl
        });
        this.dslResult = response.data;
        
        // 检查响应数据中是否有 success 字段，如果没有默认为 true
        const isSuccess = response.data.success !== undefined ? response.data.success : true;
        if (isSuccess) {
          // 确保 indexData.hits 是一个数组后再使用 forEach
          if (response.data.data && response.data.data.hits && Array.isArray(response.data.data.hits)) {
            this.indexData = response.data.data;
          } else {
            // 如果没有 hits 数组，创建一个空数组
            this.indexData = {
              hits: [],
              total: (response.data.data && response.data.data.total) || 0,
              took: (response.data.data && response.data.data.took) || 0
            };
          }
          this.showFeedback(`DSL执行成功，返回${(response.data.data && response.data.data.total) || 0}条数据，耗时${(response.data.data && response.data.data.took) || 0}ms`, 'success');
        } else {
          // 确保 response.data.message 存在
          const errorMessage = response.data.message || '未知错误';
          this.showFeedback(`DSL执行失败: ${errorMessage}`, 'error');
        }
      } catch (error) {
        console.error('执行DSL失败:', error);
        this.dslResult = {
          success: false,
          message: '执行DSL失败: ' + (error.response?.data?.message || error.message)
        };
        this.showFeedback('执行DSL失败: ' + (error.response?.data?.message || error.message), 'error');
      } finally {
        this.loading = false;
        // 发送事件通知MainContent组件执行完成
        if (this.$refs && this.$refs.mainContent) {
          this.$refs.mainContent.executingDsl = false;
        }
      }
    },
    
    clearDsl() {
      this.dslQuery = '';
      this.dslResult = null;
    },
    
    showFeedback(message, type) {
      this.feedbackMessage = message;
      this.feedbackType = type;
    },
    
    closeFeedback() {
      this.feedbackMessage = '';
    }
  },
  
  computed: {
    totalPages() {
      return Math.ceil(this.indexData.total / this.pageSize)
    }
  }
}
</script>

<style>
body {
  margin: 0;
  padding: 0;
  font-family: 'Inter', sans-serif;
  background-color: #f5f5f5;
}

#app {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.container {
  display: flex;
  flex: 1;
  overflow: hidden;
}
</style>